package com.example.a10928.weifriend.http.configuration;

import android.content.Intent;
import android.os.Looper;
import android.widget.Toast;

import com.example.a10928.weifriend.App;
import com.example.a10928.weifriend.ui.login.LoginActivity;
import com.example.a10928.weifriend.util.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.logging.Handler;

import okhttp3.Interceptor;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Chuang on 2018/2/28.
 * 请声明此类的作用，如无声明则留null
 */

public class ErrorProcessInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());
        ResponseBody body = response.body();
        String content = body.string();
        String data = content;
        try {
            JSONObject json = new JSONObject(content);
            int code = json.getInt("status_code");
            String msg = json.getString("message");
            if (code != ApiException.CODE_OK) {
                if (code == ApiException.CODE_TOKEN_PAST_DUE || code == ApiException.CODE_TOKEN_ERROR
                    || code == ApiException.CODE_NO_TOKEN||code==ApiException.BLACK_LIST||
                    code == ApiException.CODE_OTHER_LOGIN||code==ApiException.CODE_VERSION_DIFFERENT) {

                    if(App.activity!=null){
                        App.activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(code==ApiException.CODE_VERSION_DIFFERENT){
                                    Toast.makeText(App.activity, "您的App版本过低，请更新App",Toast.LENGTH_LONG).show();

                                }else{
                                    Toast.makeText(App.activity, "登录失效，请重新登录",Toast.LENGTH_LONG).show();

                                }
                            }
                        });
                    }

                    Intent intent = new Intent(Utils.getContext(), LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    Utils.getContext().startActivity(intent);
                    App.app().getUser().clearUser();
                    //完成初级验证||行名有误

                } else {
                    throw new ApiException(code, msg);
                }
            }
        } catch (JSONException e) {
            throw new ApiException(ApiException.CODE_OPERATION_FAILURE, e);
        }
        Utils.getIsNetWork().set(true);
        return response.newBuilder()
            .body(ResponseBody.create(body.contentType(), data))
            .build();

    }
}
